#!/bin/bash
## Original base found at:
## https://wiki.archlinux.org/index.php/PulseAudio/Examples#Automatically_switch_audio_to_HDMI
## udev rule expects this in /usr/local/sbin

export PATH=/usr/bin

#USER_NAME=$(who | awk -v vt=tty$(fgconsole 2>/dev/null) '$0 ~ vt {print $1}')
#USER_ID=$(id -u "${USER_NAME}")
#USER_ID=$(id -u "${USER}")
CARD_PATH="/sys/class/drm/card0/"
AUDIO_OUTPUT="analog-stereo"        ## Default if nothing in case is matched
#PULSE_SERVER="unix:/run/user/"${USER_ID}"/pulse/native"
PULSE_SERVER="unix:/run/user/"${UID}"/pulse/native"

for OUTPUT in $(cd "${CARD_PATH}" && echo card*); do
    OUT_STATUS=$(<"${CARD_PATH}"/"${OUTPUT}"/status)
    if [[ ${OUT_STATUS} == connected ]]
    then
        echo ${OUTPUT} connected
        case "${OUTPUT}" in
            "card0-DP-3")
                AUDIO_OUTPUT="hdmi-stereo-extra1"   ## thinkpad x270 dock to HDMI
            ;;
            "card0-DP-4")
                AUDIO_OUTPUT="hdmi-stereo-extra1"   ## thinkpad x270 dock to HDMI, arch
            ;;
            "card0-HDMI-A-1")
                AUDIO_OUTPUT="hdmi-stereo"          ## the 'normal' port?
            ;;
            "card0-HDMI-A-2")
                AUDIO_OUTPUT="hdmi-stereo-extra1"   ## thinkpad x270 HDMI port
            ;;
        esac
    fi
done
echo selecting output ${AUDIO_OUTPUT}
#sudo -u "${USER_NAME}" pactl --server "${PULSE_SERVER}" set-card-profile 0 output:${AUDIO_OUTPUT}+input:analog-stereo
pactl --server "${PULSE_SERVER}" set-card-profile 0 output:${AUDIO_OUTPUT}+input:analog-stereo
